/**
 * 我的服务订单
 */
let nowDate = new Date(), myServiceOrderCurrentPage = 1, pageLimit = 10, soType = 0, queryServiceOrderStatus = '', errorTip = '当前系统繁忙，请稍候再试';
let nowYear = nowDate.getFullYear() + "-", nowMonth = ((nowDate.getMonth() + 1) < 10 ? ('0' + (nowDate.getMonth() + 1)) : (nowDate.getMonth() + 1));
let nowYearMonth = nowYear + nowMonth,userBirCityCode = '',userBirAreaCode = '', userAtCityCode = '', userAtAreaCode = '', checkCodeInterval,makeMoneyIsLoaded = false,
    myInfoIsLoad = false,selStr = ' selected="selected"', doneMsg = '您确认已完成本单任务了吗', isCommented = '';
$(function(){
    //设置查询日期时间
    setQueryInputDate();
	$('.service-status span').click(function(){
        $('.service-status span').removeClass();
        $(this).addClass('service-status-selected');
        let tId = this.id;
        queryServiceOrderStatus = getStatus(tId);
        if (tId == 'issueWaitEvaluate'){
			isCommented = '0,3';
			queryServiceOrderStatus = '2,7';
		} else if (tId == 'robWaitEvaluate'){
			isCommented = '0,2';
			queryServiceOrderStatus = '2,3';
		}else {
			isCommented = '';
		}
		myServiceOrderCurrentPage = 1;
        queryMyServiceOrderData(myServiceOrderCurrentPage, pageLimit, queryServiceOrderStatus);
    });
    $('.search-button').click(function() {
    	myServiceOrderCurrentPage = 1;
    	if (this.id == 'btnDealDetailSearch') {
    		myServiceOrderCurrentPage = 1;
    		//queryMyDealLog(myServiceOrderCurrentPage,pageLimit,getDealType(''));
		}else {
			soType = this.id == 'btnIssueServiceSearch' ? 0 : 1;
	    	queryMyServiceOrderData(myServiceOrderCurrentPage, pageLimit, queryServiceOrderStatus);
		}
	});
    $('#dealType span').click(function(){
        $('#dealType span').removeClass();
        $(this).addClass('deal-type-selected');
        myServiceOrderCurrentPage = 1;
        //queryMyDealLog(myServiceOrderCurrentPage,pageLimit,getDealType(this.id));
    });
    $('#leftMenu ul li').click(function(){
        if (this.className != 'my-selected'){
            //修改标签样式
            $('#leftMenu ul li').removeClass();
            $(this).addClass('my-selected');
            let showId,hideId;
            if (this.id == 'myIssueOrder'){
                //显示我的订单对应的部分
                showId = ['issueServiceOrderSearch','issueServiceOrderDetailDiv','issueServicePageToolbar','fullPhoneMsg','issuePage'];
                hideId = ['myDealSearch','myDealDetail','myMoney','dealDetailPageToolbar','modifyMyPhoneDiv','modifyMyInfoDiv','robPage',
                          'robServiceOrderSearch','robServiceOrderDetailDiv','robServicePageToolbar','modifyMyPasswordDiv'];
				soType = 0;
				loadIssueOrRob('issueServiceOrderDetail','issueServicePage');
            }else if(this.id == 'myRobOrder'){
            	hideId = ['issueServiceOrderSearch','issueServiceOrderDetailDiv','issueServicePageToolbar','modifyMyPhoneDiv','issuePage',
            	          'myDealSearch','myDealDetail','myMoney','dealDetailPageToolbar','modifyMyInfoDiv','modifyMyPasswordDiv'];
            	showId = ['robServiceOrderSearch','robServiceOrderDetailDiv','robServicePageToolbar','fullPhoneMsg','robPage'];
            	soType = 1;
				loadIssueOrRob('robServiceOrderDetail','robServicePage');
            }else if (this.id == 'myDeal'){
                //隐藏我的订单对应的部分
                hideId = ['issueServiceOrderSearch','issueServiceOrderDetailDiv','issueServicePageToolbar','fullPhoneMsg','modifyMyPasswordDiv',
                          'robServiceOrderSearch','robServiceOrderDetailDiv','robServicePageToolbar','modifyMyInfoDiv','modifyMyPhoneDiv','issuePage','robPage'];
                showId = ['myDealSearch','myDealDetail','myMoney','dealDetailPageToolbar'];
                myServiceOrderCurrentPage = 1;
                //queryMyDealLog(myServiceOrderCurrentPage,pageLimit,getDealType(''));
            }else if (this.id == 'modifyMyInfo'){//修改资料
                //隐藏我的订单对应的部分
                hideId = ['issueServiceOrderSearch','issueServiceOrderDetailDiv','issueServicePageToolbar','fullPhoneMsg','issuePage','robPage',
                          'robServiceOrderSearch','robServiceOrderDetailDiv','robServicePageToolbar','modifyMyPasswordDiv',
                          'myDealSearch','myDealDetail','myMoney','dealDetailPageToolbar','modifyMyPhoneDiv'];
                showId = ['modifyMyInfoDiv'];
                initModifyMyInfoFormData();
            }else if (this.id == 'modifyMyPhone'){//修改手机
                //隐藏我的订单对应的部分
                hideId = ['issueServiceOrderSearch','issueServiceOrderDetailDiv','issueServicePageToolbar','fullPhoneMsg',
                          'robServiceOrderSearch','robServiceOrderDetailDiv','robServicePageToolbar','modifyMyPasswordDiv',
                          'myDealSearch','myDealDetail','myMoney','dealDetailPageToolbar','modifyMyInfoDiv','issuePage','robPage'];
                showId = ['modifyMyPhoneDiv'];
                initMyPhone();
            }else if (this.id == 'modifyMyPassword'){//修改密码
                //隐藏我的订单对应的部分
                hideId = ['issueServiceOrderSearch','issueServiceOrderDetailDiv','issueServicePageToolbar','fullPhoneMsg',
                          'robServiceOrderSearch','robServiceOrderDetailDiv','robServicePageToolbar','modifyMyPhoneDiv',
                          'myDealSearch','myDealDetail','myMoney','dealDetailPageToolbar','modifyMyInfoDiv','issuePage','robPage'];
                showId = ['modifyMyPasswordDiv'];
                setFootPosition();
            }
            hideObject(hideId);
            showObject(showId);
        }
    });

    //初始化已发布订单数据
    myServiceOrderCurrentPage = 1;
    queryMyServiceOrderData(myServiceOrderCurrentPage, pageLimit, queryServiceOrderStatus);
    if(navigator.userAgent.indexOf("Edge") > 0){
    	$('.middle-main .order-detail table').css({'margin-top': '14px'});//微调左侧菜单位置
    }
    $('#BIR_PROVINCE').change(function() {
    	getCityByProvince($(this).children('option:selected').val(),'BIR_CITY');
	});
    $('#BIR_CITY').change(function() {
    	getAreaByCity($(this).children('option:selected').val(),'BIR_AREA');
	});
    $('#AT_PROVINCE').change(function() {
    	getCityByProvince($(this).children('option:selected').val(),'AT_CITY');
	});
    $('#AT_CITY').change(function() {
    	getAreaByCity($(this).children('option:selected').val(),'AT_AREA');
	});
    //修改个人资料
    $('#myInfoSubmit').click(function() {
    	this.disabled = true;//设置按钮不可用，防止重复提交
    	//修改个人基本信息
    	myInfoSubmit();
	});
    $('#btnGetCheckCode').click(function() {
    	this.disabled = true;
    	let time = 60;//60秒倒计时 phoneObj = this,
    	checkCodeInterval = window.setInterval(function () {
  			time --;
  			if (time < 1) {
  				setGetCheckCodeEnable();
			}else {
				$('#btnGetCheckCode').val(time + '秒后可点击');
			}
		},1000);
    	goGetCheckCode();
	});
    //修改绑定手机号
    $('#submitNewPhone').click(function() {
    	this.disabled = true;
    	modifyMyPhone();
	});
    //修改我的密码
    $('#submitNewPassword').click(function() {
    	this.disabled = true;
    	modifyMyPassword(this);
	});
    $('.se-address').change(function () {
		$(this).find("option[value='0']").remove();
	});
});
//设置查询日期时间
function setQueryInputDate(){
	let jeArray = ['myIssueServiceOrderDate','myRobServiceOrderDate'];
	for (let g = 0; g < jeArray.length; g ++){
		$("#" + jeArray[g]).jeDate({
			format: "YYYY-MM",
			maxDate: $.nowDate(0)
		});
	}
	console.log('myIssueServiceOrderDate=' + $("#myIssueServiceOrderDate").val());
    $("#myIssueServiceOrderDate").val(nowYearMonth);
    $("#myRobServiceOrderDate").val(nowYearMonth);
}
//隐藏
function hideObject(idArray) {
	if(!isNull(idArray) && idArray.length > 0){
		for (let i = 0; i < idArray.length; i++) {
			$('#' + idArray[i]).hide();
		}
	}
}
//显示
function showObject(idArray) {
	if(!isNull(idArray) && idArray.length > 0){
		for (let i = 0; i < idArray.length; i++) {
			$('#' + idArray[i]).show();
		}
	}
}
/**
 * 查询服务订单数据
 * @param currentPage
 * @param pageSize
 * @param soStatus
 */
function queryMyServiceOrderData(currentPage, pageSize, soStatus) {
	let soName = V('myIssueServiceTitle'), soOrderDate = '', soServiceDate = '';
	if (soType == 0) {
		soOrderDate = V('myIssueServiceOrderDate');
		if (isNull(soOrderDate)) {
			alert('日期不能为空');
			return;
		}
	}else if (soType == 1) {
		soName = V('myRobServiceTitle');
		soServiceDate = V('myRobServiceOrderDate');
		if (isNull(soServiceDate)) {
			alert('日期不能为空');
			return;
		}
	}
	showCloseTip(true,'正在加载数据,请稍候...');
	$.ajax({
		type: 'post',
		url: '/serviceOrder/queryMyServiceOrder',
		dataType: 'json',
		async: false,
		timeout: 30000,
		global: false,//不触发全局 AJAX 事件
		data: {
			soStatus: soStatus,
			isCommented: isCommented,
			soType: soType,
			soOrderDate: soOrderDate,
			soServiceDate: soServiceDate,
			currentPage: currentPage,
			showCount: pageSize,
			name: soName == '输入标题...' ? '' : soName
		},
		success: function(myOrderPage) {
			appendMyOrderHtml(myOrderPage,currentPage);
		},
		error: function(result) {
			setFootPosition();
			showErrorMsg(result);
			showCloseTip(false,'');
		}
	});
}

/**
 * 添加我的订单HTML
 * @param myOrderPage 我的订单page对象
 */
function appendMyOrderHtml(myOrderPage,currentPage) {
	let appendStr = '', soTotalPage = 0;
	if (myOrderPage.status == '0') {
		queryMyMakeMoney();
		//服务订单数据
		let myPi = myOrderPage.myPi;
		let serviceOrderArray = myPi.list, totalRows = 0, totalAmount = 0;
		let soaLen = serviceOrderArray.length;
		if (soaLen < 1){
			appendStr += '<tr height="40px"><td colspan="8">无服务订单</td></tr>';
		}
		for (let s = 0; s < soaLen; s++) {
			let order = serviceOrderArray[s];
			totalRows ++;
			totalAmount += parseFloat(order.soAmount);
			let showBillNo = order.billNumber,notFullPhone = '', myStatus = order.soStatus;
			let myBillNo = showBillNo;
			showBillNo = showBillNo.substring(0,4) + ' ' + showBillNo.substring(4,8) + ' ' + showBillNo.substring(8,12);
			let otherFullPhone = soType == 0 ? order.robPhone : order.issuePhone;
			if (isNull(otherFullPhone)) {
				otherFullPhone = '';
			}else {
				notFullPhone = otherFullPhone.substr(0,3) + '****' + otherFullPhone.substr(7,11);
			}

			appendStr += '<tr height="40px">'+
				'<td><a style="text-decoration:underline;" target="_blank" href="orderDetail.html?oid=' + myBillNo + '">' + showBillNo + '</a></td>' +
				'<td>' + order.soName + '</td>'+
				'<td>' + order.soOrderDate + '</td>'+
				'<td>' + order.soServiceDate + '</td>'+
				'<td title="' + otherFullPhone + '">' + notFullPhone + '</td>'+
				'<td>' + order.soAmount + '</td>'+
				'<td>' + order.soAddress + '</td>';
			let soStatus = '', iAmOperate = '', isCommented = order.isCommented,btnDeleteStr = '',
				deleteFun = 'onclick="deleteOrder(\'' + myBillNo + '\',this)">删除';
			if(myStatus == '1'){
				soStatus = '未完成';
				if (soType == 1) {//已抢订单服务
					iAmOperate = 'onclick="robberDoneOrder(\'' + myBillNo + '\',this)">完成';
				}else {
					soStatus = '已被抢';
				}
			}else if (myStatus == '2') {
				soStatus = '已完成';
				if(isCommented == '0' || (isCommented == '3' && soType == 0) || (isCommented == '2' && soType == 1)){
					iAmOperate = 'onclick="rateUser(\'' + myBillNo + '\')">评价';
				}else if (isCommented == '1' || (isCommented == '2' && soType == 0) || (isCommented == '3' && soType == 1)) {
					iAmOperate = deleteFun;
				}
				if (iAmOperate != deleteFun) {
					btnDeleteStr = '<button class="btn-done-order" ' + deleteFun + '</button>';
				}
			}else if (myStatus == '3') {//发布人删除，抢单人未删除
				soStatus = '已完成';
				//已抢订单
				if (soType == 1) {
					if(isCommented == '0' || isCommented == '2'){
						iAmOperate = 'onclick="rateUser(\'' + myBillNo + '\')">评价';
					}
					btnDeleteStr = '<button class="btn-done-order" ' + deleteFun + '</button>';
				}
			}else if (myStatus == '4') {
				soStatus = '待确认';
				//已发布订单服务
				if (soType == 0) {
					iAmOperate = 'onclick="issuerDoneOrder(\'' + myBillNo + '\',this)">完成';
				}
			}else if (myStatus == '5') {
				soStatus = '已取消';
				iAmOperate = deleteFun;
			}else if (myStatus == '6') {
				soStatus = '已过期';
				iAmOperate = deleteFun;
			}else if (myStatus == '0') {
				soStatus = '未被抢';
				iAmOperate = 'onclick="cancelOrder(\'' + myBillNo + '\',this)">取消';
			}else if (myStatus == '7') {
				soStatus = '已完成';
				//发布订单
				if (soType == 0) {
					if(isCommented == '0' || isCommented == '3'){
						iAmOperate = 'onclick="rateUser(\'' + myBillNo + '\')">评价';
					}
					btnDeleteStr = '<button class="btn-done-order" ' + deleteFun + '</button>';
				}
			}
			appendStr += '<td>' + soStatus + '</td>';
			if (isNull(iAmOperate) && isNull(btnDeleteStr)){
				appendStr += '<td>—</td></tr>';
			} else if (isNull(iAmOperate) && !isNull(btnDeleteStr)){
				appendStr += '<td>' + btnDeleteStr + '</td></tr>';
			} else {
				btnDeleteStr = isNull(btnDeleteStr) ? '' : '&nbsp;&nbsp;' + btnDeleteStr;
				appendStr += '<td><button class="btn-done-order" ' + iAmOperate + '</button>' + btnDeleteStr + '</td></tr>';
			}
		}
		soTotalPage = parseInt(myPi.pages);//总页数
		let ellipsisLi = '<li style="width: 14px;color: #b42323;fonts-weight: 800;">…</li>',
			pageNums = myPi.navigatepageNums, aHref = 'href="javascript:void(0)"';
		let firstClass = 'first-page', previousClass = 'previous-page', isHave = '';
		//如果没有上一页
		if (!myPi.hasPreviousPage) {
			firstClass = 'no-first';
			previousClass = 'no-previous';
			isHave = 'no-have';
		}
		let pageAppendStr = '<li title="第一页" class="' + firstClass + '"><a ' + aHref + ' class="first ' + isHave + '"></a></li>' +
			'<li title="上一页" class="' + previousClass + '"><a ' + aHref + ' class="previous ' + isHave + '"></a></li>';
		if (pageNums[0] > 1){
			pageAppendStr += ellipsisLi;
		}
		if (soTotalPage > 0) {
			for (let g = 0; g < pageNums.length; g ++) {
				let currentClass = pageNums[g] == currentPage ? 'current' : 'have';
				pageAppendStr += '<li><a ' + aHref + ' class="page ' + currentClass + '">' + pageNums[g] + '</a></li>';
			}
		}
		if (pageNums[pageNums.length - 1] < myPi.pages){
			pageAppendStr += ellipsisLi;
		}
		let nextClass = 'next-page', lastClass = 'last-page';
		isHave = '';
		//如果没有下一页
		if (!myPi.hasNextPage){
			nextClass = 'no-next';
			lastClass = 'no-last';
			isHave = 'no-have';
		}
		pageAppendStr += '<li title="下一页" class="' + nextClass + '"><a ' + aHref + ' class="next ' + isHave + '"></a></li>' +
			'<li title="最后一页" class="' + lastClass + '"><a ' + aHref + ' class="last ' + isHave + '"></a></li>';
		let issueBody = $('#issueServiceOrderDetail tbody'), robBody = $('#robServiceOrderDetail tbody');
		let isp = $('#issueServicePage'), rsp = $('#robServicePage');
		if (soType == 0) {//发布服务
			$('#issueTotalCount').text(totalRows);
			$('#issueTotalAmount').text(totalAmount.toFixed(2));
			issueBody.children().remove();
			issueBody.append(appendStr);
			isp.children().remove();
			isp.append(pageAppendStr);
			$('#issueTotalNum').text(myPi.total);
			$('#issueTotalPages').text(soTotalPage);
		}else {
			$('#robTotalCount').text(totalRows);
			$('#robTotalAmount').text(totalAmount.toFixed(2));
			robBody.children().remove();
			robBody.append(appendStr);
			rsp.children().remove();
			rsp.append(pageAppendStr);
			$('#robTotalNum').text(myPi.total);
			$('#robTotalPages').text(soTotalPage);
		}
	}
	let leftCss = 'border-left-color', rightCss = 'border-right-color';
	$(".first-page").mouseover(function () {
		$(this).css(leftCss, "#ffa12d");
	}).mouseout(function () {
		$(this).css(leftCss, '#b42323');
	});
	$(".last-page").hover(function () {
		$(this).css(rightCss, "#ffa12d");
	}).mouseout(function () {
		$(this).css(rightCss, '#b42323');
	});
	pageAddClickEvent('issueServicePage',currentPage,soTotalPage);
	pageAddClickEvent('robServicePage',currentPage,soTotalPage);
	setFootPosition();
	showCloseTip(false,'');
}
/**
 * 设置页脚位置
 */
function setFootPosition() {
	let foot = $('#footer'),hh = $('header').height(), rh = $('.roll-word').height(),
		sh = $('#issueServiceOrderSearch').height(), ih = $('#issueServiceOrderDetailDiv').height(),fh = foot.height();
	if (isSelect('myRobOrder')) {
		ih = $('#robServiceOrderDetailDiv').height();
	}else if(isSelect('modifyMyInfo')){
		ih = $('#modifyMyInfoDiv').height();
	}else if(isSelect('modifyMyPhone')){
		ih = $('#modifyMyPhoneDiv').height();
	}else if(isSelect('modifyMyPassword')){
		ih = $('#modifyMyPasswordDiv').height();
	}
	let footerBottom = $(window).height() - hh - rh - sh - ih - fh;
	if (footerBottom > 60) {
		foot.css({'bottom':'0','position':'fixed'});
	}else {
		foot.css('position','static');
	}
}
function isSelect(id) {
	return $('#' + id)[0].className.indexOf('my-selected') > -1;
}
//获取状态
function getStatus(type) {
	if (type == 'issueAllStatus' || type == 'robAllStatus') {
		return '';
	}else if (type == 'issueWaitService' || type == 'robWaitService') {
		return '1';
	}else if (type == 'issueComplete' || type == 'robComplete') {
		return soType == 0 ? '2,7' : '2,3';
	}else if (type == 'issueWaitSure' || type == 'robWaitSure') {
		return '4';
	}
	return '0';
}

/**
 * 显示错误信息
 * @param result
 */
function showErrorMsg(result) {
	showLglTipsBox(300,70,'系统提示',errorTip,false);
}

//查询交易日志
function queryMyMakeMoney() {
	//如果已经加载了，则不再加载
	if (makeMoneyIsLoaded) {
		return;
	}
	$.ajax({
		type: 'post',
		url: '/serviceOrder/myMakeMoney',
		dataType: 'json',
		async: false,
		timeout: 30000,
		success: function(result) {
			if (result.status == '0') {
				makeMoneyIsLoaded = true;
				//服务订单数据
				$('.roll-word').text('我  已  经  赚  了  ' + result.totalMakeMoney + '  元');
			}
		},
		error: function() {
			showLglTipsBox(300,70,'系统提示',errorTip,false);
		}
	});
}
/**
 * 抢单人完成已抢订单
 * @param robedBillNo 抢单完成的订单编号
 * @param btnObj 用户点击的抢单人完成的按钮对象
 */
function robberDoneOrder(robedBillNo,rdBtn) {
	if(!confirm(doneMsg)) {
		return;
	}
	setBtnState(rdBtn,true);
	$.ajax({
		type: 'post',
		url: '/serviceOrder/robberDoneOrder',
		dataType: 'json',
		data: {
			billNumber: robedBillNo
		},
		timeout: 30000,
		success: function(r) {
			if (r == '0') {
			    alert('订单处理成功，但仍需对方确认');
				let rdBtnTd = $(rdBtn).parent('td');
                rdBtnTd.prev().html('待确认');
				rdBtnTd.html('—');
                rdBtn.remove();
			}else {
				alert('订单处理失败');
			}
			setBtnState(rdBtn,false);
		},
		error: function() {
			alert(errorTip);
			setBtnState(rdBtn,false);
		}
	});
}
/**
 * 发布人完成已抢订单
 * @param robedBillNo 被抢单号
 * @param btnObj 按钮
 */
function issuerDoneOrder(robedBillNo,idBtn) {
    if(!confirm(doneMsg)) {
        return;
    }
    setBtnState(idBtn,true);
    $.ajax({
        type: 'post',
        url: '/serviceOrder/issuerDoneOrder',
        dataType: 'json',
        data: {billNumber: robedBillNo},
        timeout: 30000,
        success: function(r) {
            if (r == '0') {
                alert('订单处理成功，快去评论一下人家吧');
                let btnObjTd = $(idBtn).parent('td');
                btnObjTd.prev().html('已完成');
                idBtn.remove();
                //添加评价、删除按钮
                btnObjTd.html('<button class="btn-done-order" onclick="rateUser(\'' + robedBillNo + '\')">评价</button>'
                    + '&nbsp;&nbsp;<button class="btn-done-order" onclick="deleteOrder(\'' + robedBillNo + '\',this)">删除</button>');
            }else {
                alert('订单处理失败');
            }
            setBtnState(idBtn,false);
        },
        error: function() {
            alert(errorTip);
            setBtnState(idBtn,false);
        }
    });
}
/**
 * 取消未抢订单
 * @param robedBillNo 要评价的订单号
 * @param btnObj 取消订单操作按钮对象
 * @returns
 */
function cancelOrder(cancelBillNo,btnObj) {
	if(!confirm('取消操作将会影响您在本平台的信誉等级，您确认要取消吗？')) {
		return;
	}
	setBtnState(btnObj,true);
    showLoading('正在取消...');
	$.ajax({
		type: 'post',
		url: '/serviceOrder/cancelServiceOrder',
		dataType: 'json',
		data: {
			billNumber: cancelBillNo
		},
		timeout: 30000,
		success: function(cancelResult) {
			if (cancelResult == '0') {
				alert('订单取消成功');
				$(btnObj).parent('td').prev().html('已取消');
                $(btnObj).attr('onclick','deleteOrder(\'' + cancelBillNo + '\',this)').text('删除');
			}else if (cancelResult == '2') {
				alert('订单不存在');
			}else if (cancelResult == '3') {
				alert('订单不是未抢状态');
			}else if (cancelResult == '4') {
				alert('该订单不是您发布的，无权取消');
			}else {
				alert('订单取消失败');
			}
			setBtnState(btnObj,false);
            hideLoading();
		},
		error: function() {
			alert(errorTip);
			setBtnState(btnObj,false);
            hideLoading();
		}
	});
}

/**
 * 删除订单
 * @param delBillNo 要删除的订单编号
 */
function deleteOrder(delBillNo,delBtn) {
	if(!confirm('删除后将不再显示，您确认要删除此订单吗？')) {
		return;
	}
	showLoading('正在删除...');
	$.ajax({
		type: 'post',
		url: '/serviceOrder/deleteOrder',
		dataType: 'json',
		data: {
			billNumber: delBillNo
		},
		timeout: 30000,
		success: function(dr) {
			if (dr == '0') {
				alert('订单删除成功');
				totalNumSubtractOne();
				$(delBtn).parent('td').parent('tr').remove();
			}else {
				alert('订单删除失败');
			}
			hideLoading();
		},
		error: function() {
			alert(errorTip);
			hideLoading();
		}
	});
}
/**
 * 显示加载信息
 * @param loadStr 加载文字
 */
function showLoading(loadStr) {
    $('.page-mask,.loading').show();
    $('#loadingWord').text(loadStr);
}
function hideLoading() {
    $('.page-mask,.loading').hide();
}
/**
 * 设置按钮状态
 * @param btn
 * @param isDis true:不可用，false:可用
 */
function setBtnState(btn,isDis) {
	$(btn).attr("disabled", isDis);
	btn.style.backgroundColor = isDis ? '#cccccc' : '#ffa12d';
}
/**
 * 评价用户
 * @param soBillNo 要评价的订单编号
 * @returns
 */
function rateUser(soBillNo) {
	sessionStorage.setItem('userRateBillNo', soBillNo);
	sessionStorage.setItem('rateIssueOrRob', soType);
	window.location.href = '/userPages/userRate.html';
}

/*
 * 初始化修改资料表单数据
 */
function initModifyMyInfoFormData(){
    $('.middle-main').css({'background-color': '#FFFFFF'});
    //如果已经加载过一次了，则不再重新加载
    if (myInfoIsLoad) {
        setFootPosition();
        return;
    }
    showCloseTip(true, '正在加载您的资料...');
    $.ajax({
        type: 'post',
        url: '/index/user/seeMyOtherInfo',
        dataType: 'json',
        timeout: 30000,
        success: function (result) {
			if (result.status == '3') {
				alert('登录失效，请重新登录');
				window.location.href = 'userLogin.html';
				return;
			}else if (result.status != '0') {
                alert('获取您的资料失败，请稍候再试');
                return;
            }
            //初始化下生日的年月日下拉框
            let u = result.uoi, selectedStr = '';
            let maxYears = nowDate.getFullYear(), minYears = 1930,
                myBirthday = isNull(u.BIRTHDAY) ? '' : u.BIRTHDAY;
            userBirCityCode = u.BIR_CITY;
            userBirAreaCode = u.BIR_AREA;
            userAtCityCode = u.AT_CITY;
            userAtAreaCode = u.AT_AREA;
            I('nickName').value = u.nickName;
            I('EMAIL').value = u.EMAIL;
            $('#SEX').val(u.SEX);
            let myBirthdayArray = myBirthday.split('-');
            //设置生日年份下拉框
            for (let g = maxYears; g >= minYears; g--) {
                selectedStr = g == myBirthdayArray[0] ? ' selected="selected"' : '';
                $('#YEAR').append('<option value="' + g + '"' + selectedStr + '>' + g + '</option>');
            }
			let dateIsSelect = false;
            //设置生日月份下拉框
            for (let g = 1; g <= 12; g++) {
				let month = g < 10 ? ('0' + g) : g;
				dateIsSelect = myBirthdayArray.length > 1 && g == myBirthdayArray[1];
				selectedStr = dateIsSelect ? ' selected="selected"' : '';
                $('#MONTH').append('<option value="' + month + '"' + selectedStr + '>' + month + '</option>');
            }
            //设置生日某天下拉框
            for (let g = 1; g <= 31; g++) {
				let day = g < 10 ? ('0' + g) : g;
				dateIsSelect = myBirthdayArray.length > 2 && g == myBirthdayArray[2];
				selectedStr = dateIsSelect ? ' selected="selected"' : '';
                $('#DAY').append('<option value="' + day + '"' + selectedStr + '>' + day + '</option>');
            }
            //清空下拉框
            emptySelect();
			let bloodTypeArray = getDictionaries(81);
            //设置血型
            for (let g = 0; g < bloodTypeArray.length; g++) {
				let bt = bloodTypeArray[g].dicName;
                selectedStr = bt == u.BLOOD_TYPE ? ' selected="selected"' : '';
                $('#BLOOD_TYPE').append('<option value="' + bt + '"' + selectedStr + '>' + (bt == 'T' ? '其它' : bt) + '</option>');
            }
            appendMyOccupation(getDictionaries(52), u.occId);
			let myProvinceArray = getProvinces('', '');
            appendProvince(myProvinceArray, u.BIR_PROVINCE, 'BIR_PROVINCE');
            appendProvince(myProvinceArray, u.AT_PROVINCE, 'AT_PROVINCE');
            getCityByProvince(u.BIR_PROVINCE, 'BIR_CITY');
            getCityByProvince(u.AT_PROVINCE, 'AT_CITY');
            showCloseTip(false, '');
            myInfoIsLoad = true;
        },
        error: function (result) {
            showCloseTip(false, '');
        }
    });
	setFootPosition();
}
function emptySelect() {
    $('#BLOOD_TYPE,#OCCUPATION,#BIR_PROVINCE,#AT_PROVINCE,#BIR_CITY,#AT_CITY').empty();
}
//通过省编号获取该省下的地级市
function getCityByProvince(provinceCode, appendById) {
	if(isNull(provinceCode)) {
		return;
	}
	let sessionCityArray = localStorage.getItem('ALL_CITY_' + provinceCode);
	if (!isNull(sessionCityArray)  && sessionCityArray != 'undefined') {
		appendCityOption(JSON.parse(sessionCityArray), appendById);
		return;
	}
	$.ajax({
		type: 'post',
		url: '/index/address/queryCityList?provinceCode=' + provinceCode,
		dataType: 'json',
		async: false,
		timeout: 30000,
		success: function(result) {
			if (!isNull(result.cityList)) {
				localStorage.setItem('ALL_CITY_' + provinceCode, JSON.stringify(result.cityList));
				appendCityOption(result.cityList, appendById);
			}else {
				alert('获取城市列表失败');
			}
		},
		error: function(result) {
			alert('系统繁忙，请稍候再试');
		}
	});
}
/**
 * 添加城市列表下拉框
 * @param cityArray
 * @param appendById
 * @returns
 */
function appendCityOption(cityArray,appendById) {
	let cityOpArr = [], selectedCity = '', defCityCode = '', areaId = '';
    for (let g = 0; g < cityArray.length; g ++){
    	let cityObj = cityArray[g];
    	let ctCode = cityObj.cityCode;
    	if((ctCode == userBirCityCode && appendById == 'BIR_CITY') ||
    			(ctCode == userAtCityCode && appendById == 'AT_CITY')){
    		selectedCity = ' selected="selected"';
			defCityCode = ctCode;
    	}else {
    		selectedCity = '';
		}
		cityOpArr.push('<option value="' + ctCode + '"' + selectedCity + '>' + cityObj.cityName + '</option>');
    }
    $('#' + appendById).empty().append(cityOpArr.join(''));
    if(isNull(defCityCode)){
		defCityCode = cityArray[0].cityCode;
    }
	areaId = appendById == 'BIR_CITY' ? 'BIR_AREA' : 'AT_AREA';
    getAreaByCity(defCityCode, areaId);
}
/**
 * 添加区县列表下拉框
 * @param areaArray
 * @param appendById
 * @returns
 */
function appendAreaOption(areaArray,appendById) {
	let areaOpArr = [], selectedArea = '';
    for (let g = 0; g < areaArray.length; g ++){
    	let areaObj = areaArray[g];
    	let arCode = areaObj.areaCode;
    	if((arCode == userBirAreaCode && appendById == 'BIR_AREA') ||
			(arCode == userAtAreaCode && appendById == 'AT_AREA')){
    		selectedArea = ' selected="selected"';
    	}else {
    		selectedArea = '';
		}
		areaOpArr.push('<option value="' + arCode + '"' + selectedArea + '>' + areaObj.areaName + '</option>');
    }
    $('#' + appendById).empty().append(areaOpArr.join(''));
}
//通过城市编号获取该城市下的区县
function getAreaByCity(cityId, appendById) {
	if(isNull(cityId)) {
		return;
	}
	let sessionAreaArray = sessionStorage.getItem(cityId);
	if (!isNull(sessionAreaArray) && sessionAreaArray != 'undefined') {
		appendAreaOption(JSON.parse(sessionAreaArray), appendById);
		return;
	}
	$.ajax({
		type: 'post',
		url: '/index/address/listArea?cityCode=' + cityId,
		dataType: 'json',
		timeout: 30000,
		success: function(result) {
			if (!isNull(result)) {
				sessionStorage.setItem(cityId, JSON.stringify(result));
				appendAreaOption(result, appendById);
			}else {
				alert('获取区县列表失败');
			}
		}
	});
}
//修改个人基本信息
function myInfoSubmit() {
	let myEmail = V('EMAIL'), btnMyInfo = I('myInfoSubmit');
	//如果邮箱不为空，并且验证不通过
	if (!isNull(myEmail) && !checkEmail(myEmail)) {
		btnMyInfo.disabled = false;
		alert('邮箱格式不正确');
		return;
	}
	$.ajax({
		type: 'post',
		url: '/index/user/editUserInfo',
		dataType: 'json',
		data: {
            nickName: V('nickName'),
			SEX: V('SEX'),
			BIRTHDAY: (V('YEAR') + '-' + V('MONTH') + '-' + V('DAY')),
			BLOOD_TYPE: V('BLOOD_TYPE'),
			OCCUPATION: V('OCCUPATION'),
			BIR_PROVINCE: getVal('BIR_PROVINCE'),
			BIR_CITY: getVal('BIR_CITY'),
			BIR_AREA: getVal('BIR_AREA'),
			AT_PROVINCE: getVal('AT_PROVINCE'),
			AT_CITY: getVal('AT_CITY'),
			AT_AREA: getVal('AT_AREA'),
			EMAIL: myEmail
		},
		timeout: 30000,
		success: function(result) {
			if (result.status == '3') {
				alert('登录失效，请重新登录');
				window.location.href = 'userLogin.html';
				return;
			}
			btnMyInfo.disabled = false;
			if (result.status == '0') {
				$('#myUserName').text(V('nickName'));
				alert('资料修改成功');
			}else {
				alert('资料修改失败');
			}
		},
		error: function() {
			alert('系统繁忙，请稍候再试');
			btnMyInfo.disabled = false;
		}
	});
}
function getVal(id) {
	return V(id) == '0' ? '' : V(id);
}
/**
 * 初始化我的手机号码
 * @returns
 */
function initMyPhone() {
	let myPhone = sessionStorage.getItem(SCS_USER_PHONE);
	if (isNull(myPhone)) {
		$.ajax({
			type: 'post',
			url: '/index/user/getLoginUserPhone',
			dataType: 'json',
			async: false,
			timeout: 30000,
			success: function(phoneData) {
				if (phoneData.status == '0') {
					myPhone = phoneData.myPhone;
					sessionStorage.setItem(SCS_USER_PHONE,myPhone);
				}else {
					alert('您当前没有手机号码');
				}
			},
			error: function() {
				alert('系统繁忙，请稍候再试');
			}
		});
	}
	if (!isNull(myPhone)){
		myPhone = myPhone.substring(0, 3) + "*****" + myPhone.substring(8, 11);
		I('myOldPhone').value = myPhone;
	}
	setFootPosition();
}
//获取验证码
function goGetCheckCode() {
    let waitGetCode = '当前系统繁忙,请稍后再获取验证码', pem = $('#phoneErrorMsg');
	$.ajax({
        type: "POST",
        url: '/index/user/sendCodeByLogin',
        dataType: 'json',
        success: function(sendResult) {
			let rs = sendResult.status;
        	if(rs != '1'){
				setGetCheckCodeEnable();
			}
			if(rs == '3'){
				alert('登录失效，请重新登录');
				window.location.href = 'userLogin.html';
			}else if(rs == '1'){
				pem.text('验证码已发送,20分钟内有效');
        	}else if(rs == '4'){
				pem.text('您当前IP地址获取验证码次数过多，请稍候再试');
        	}else if(rs == '5'){
				pem.text('您当前手机号码获取验证码次数过多，请稍候再试');
        	}else {
				pem.text(waitGetCode);
			}
        },
        error: function() {
        	pem.text(waitGetCode);
        	setGetCheckCodeEnable();
		}
    });
}

/**
 * 校验修改我的手机号
 * @param myNewPhone 新手机号
 * @param checkCode 验证码
 */
function checkModifyMyPhone(myNewPhone,checkCode) {
    if(isNull(checkCode)){
        return '验证码不能为空';
    }
    if(isNull(myNewPhone)){
        return '新手机号不能为空';
    }
    if(checkCode.length != 6){
        return '验证码码错误';
    }
    if(!phoneNumberIsRight(myNewPhone)){
        return '新手机号码格式不对';
    }
    if (myNewPhone == sessionStorage.getItem(SCS_USER_PHONE)){
        return '新手机号不能跟原手机号相同';
    }
    return '';
}
/**
 * 修改手机号码
 */
function modifyMyPhone() {
	let myNewPhone = V('myNewPhone'), checkCode = V('oldPhoneCheckCode');
	let errMsg = checkModifyMyPhone(myNewPhone,checkCode);
	if (errMsg.length > 1){
	    alert(errMsg);
        I('submitNewPhone').disabled = false;
        return;
    }
	$.ajax({
        type: "POST",
        url: '/index/user/modifyMyPhone',
        dataType: 'json',
        data: {
        	newPhone: myNewPhone,
        	checkCode: checkCode
		},
        success: function(res) {
        	I('submitNewPhone').disabled = false;
        	if(res == '0'){
        		sessionStorage.setItem(SCS_USER_PHONE, myNewPhone);
        		I('oldPhoneCheckCode').value = '';
        		I('myNewPhone').value = '';
        		alert('手机号码修改成功');
        		I('myOldPhone').value = myNewPhone.substring(0,3) + '****' + myNewPhone.substring(7,11);
        	}else if(res == '1'){
        		alert('手机号码修改时出错');
        	}else if(res == '2'){
                alert('该手机号已被注册');
            }else if(res == '3'){
        		alert('您登录已失效，请重新登录');
        	}else if(res == '4'){
        		alert('未获取验证码');
        	}else if(res == '5'){
        		alert('验证码失效或不正确');
        	}else if(res == '6'){
				alert('未获取到手机号码');
			}else if(res == '7'){
                alert('新手机号不能跟原手机号相同');
            }else {
        		alert('手机号码修改失败');
			}
        },
        error: function() {
        	alert(errorTip);
        	I('submitNewPhone').disabled = false;
		}
    });
}
/**
 * 设置或许验证码按钮可用
 * @returns
 */
function setGetCheckCodeEnable() {
	window.clearInterval(checkCodeInterval);
	$('#btnGetCheckCode').val('获取验证码');
	$('#phoneErrorMsg').text('');
	I('btnGetCheckCode').disabled = false;
}

/**
 * 校验修改我的密码
 * @param myOldPassword 原密码
 * @param myNewPassword 新密码
 * @param sureNewPassword 确认新密码
 * @returns {string} 校验的结果字符串
 */
function checkModifyMyPassword(myOldPassword,myNewPassword,sureNewPassword) {
    if (isNull(myOldPassword)) {
        return '原密码不能为空';
    }
    if (myOldPassword.length < 6) {
        return '原密码错误';
    }
    if (isNull(myNewPassword) || isNull(sureNewPassword)) {
        return '新密码和确认密码都不能为空';
    }
    if (myNewPassword.length < 6) {
        return '新密码长度不能少于6位数';
    }
    if (myOldPassword == myNewPassword) {
        return '新密码不能和原密码相同';
    }
    if (myNewPassword != sureNewPassword) {
        return '新密码和确认密码不相等';
    }
    return '';
}
/**
 * 修改我的密码
 */
function modifyMyPassword(btnModifyPwd) {
	let myOldPassword = V('myOldPassword'),myNewPassword = V('myNewPassword'), sureNewPassword = V('sureNewPassword'),
	pwdError = $('#passwordErrorMsg');
	let checkResult = checkModifyMyPassword(myOldPassword,myNewPassword,sureNewPassword);
    if (checkResult.length > 1) {
        pwdError.text(checkResult);
        btnModifyPwd.disabled = false;
        return;
    }
	let newPwdObj = new jsSHA("SHA-1", "TEXT"), oldPwdObj = new jsSHA("SHA-1", "TEXT");
	newPwdObj.update(myNewPassword);
	myNewPassword = newPwdObj.getHash("HEX");
	oldPwdObj.update(myOldPassword);
	myOldPassword = oldPwdObj.getHash("HEX");
	$.ajax({
        type: "POST",
        url: '/index/user/editUserInfo',
        dataType: 'json',
        data: {
        	oldPwd: myOldPassword,
        	newPwd: myNewPassword
		},
        success: function(modifyResult) {
        	let s = modifyResult.status, errMsg = '密码修改失败';
        	btnModifyPwd.disabled = false;
        	if(s == '0'){
                errMsg = '密码修改成功';
        		I('myOldPassword').value = '';
        		I('myNewPassword').value = '';
        		I('sureNewPassword').value = '';
        	}else if(s == '1'){
				errMsg = errorTip;
            }else if(s == '2'){
				errMsg = '原密码错误';
        	}else if(s == '3'){
				errMsg = '您登录已失效，请重新登录';
        	}
			pwdError.text(errMsg);
        },
        error: function() {
			pwdError.text(errorTip);
        	btnModifyPwd.disabled = false;
		}
    });
	setFootPosition();
}

/**
 * 添加职业信息
 * @param occArray
 * @param myOccId
 */
function appendMyOccupation(occArray,myOccId) {
	if(isNull(occArray)){
		return;
	}
	for (var g = 0; g < occArray.length; g ++){
		var occId = occArray[g].id;
		$('#OCCUPATION').append('<option value="' + occId + '"' + (occId == myOccId ? selStr : '') + '>' + occArray[g].dicName + '</option>');
	}
}
/**
 * 添加省份信息
 * @param pArray
 * @param pId
 * @param appendId
 */
function appendProvince(pArray,pId,appendId) {
	let pa = [];
	for (let g = 0; g < pArray.length; g ++){
		let pvCode = pArray[g].provinceCode;
		pa.push('<option value="' + pvCode + '"' + (pvCode == pId ? selStr : '') + '>' + pArray[g].provinceName + '</option>');
	}
	$('#' + appendId).append(pa.join(''));
}

/**
 * 显示或关闭提示
 * @param isShow
 * @param tip
 */
function showCloseTip(isShow,tip) {
	var tipObj = $('.page-mask,.loading');
	if (isShow){
		tipObj.show();
		$('#loadingWord').text(tip);
		return;
	}
	tipObj.hide();
}

function loadIssueOrRob(tableId,pageId) {
	$('.middle-main').css('background-color','');
	//如果还没有加载
	if ($('#' + tableId + ' tbody').find('tr').length == 0) {
		myServiceOrderCurrentPage = 1;
		queryServiceOrderStatus = '';
		queryMyServiceOrderData(myServiceOrderCurrentPage, pageLimit, queryServiceOrderStatus);
		return;
	}
	$('#' + pageId + ' a').each(function(index) {
		if (this.className.indexOf('current') > 0) {
			myServiceOrderCurrentPage = parseInt(this.innerText);
			return false;
		}
	});
    setFootPosition();
}

/**
 * 分页按钮添加点击事件
 * @param pageId
 */
function pageAddClickEvent(pageId,currentPage,totalPage) {
	$('#' + pageId + ' a').unbind('click').click(function() {
		var className = this.className;
		if (className.indexOf('no-have') == -1 && className.indexOf('current') < 0) {
			if(className.indexOf('first') > -1) {
				currentPage = 1;
			}else if(className.indexOf('previous') > -1){
				currentPage = currentPage > 1 ? currentPage - 1 : 1;
			}else if(className.indexOf('next') > -1){
				currentPage = currentPage < totalPage ? currentPage + 1 : totalPage;
			}else if(className.indexOf('last') > -1){
				currentPage = totalPage;
			}else {
				currentPage = parseInt(this.innerText);
			}
			queryMyServiceOrderData(currentPage, pageLimit,queryServiceOrderStatus);
		}
	});
}

/**
 * 点击月份控制里的“确定”按钮时，执行查询，注：此函数名不可修改，否则会失效
 */
function setOkFunc() {
    myServiceOrderCurrentPage = 1;
    queryMyServiceOrderData(myServiceOrderCurrentPage, pageLimit, queryServiceOrderStatus);
}

/**
 * 总记录数减1，注：总页数、分页的页号数字暂时没改
 */
function totalNumSubtractOne() {
	let menuId = $('#leftMenu .my-selected').attr('id'), totalNumId = 'robTotalNum';
	//如果是发布订单（页面总记录要减1）
	if (menuId == 'myIssueOrder'){
		totalNumId = 'issueTotalNum';
	}
	let totalNum = $('#' + totalNumId).text();
	$('#' + totalNumId).text(parseInt(totalNum) - 1);
}